package com.nowcoder.community.util;


//import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@Component
public class SensitiveFilter {
    private static final Logger logger = LoggerFactory.getLogger(SensitiveFilter.class);
    //替换的符号
    private static final String REPLACEMENT = "***";
    //定义前缀树
    private class TrieNode{
        //关键词结束表示
        private boolean isKeyWordEnd = false;
        //子节点(key是下级字符，value是下级节点)
        private Map<Character, TrieNode> subNodes = new HashMap<>();

        //添加子节点
        public void addSubNode(Character key, TrieNode value){
            subNodes.put(key, value);
        }

        //获取子节点
        public TrieNode getSubNode(Character key){
            return subNodes.get(key);
        }

        public boolean isKeyWordEnd() {
            return this.isKeyWordEnd;
        }

        public void setKeyWordEnd(final boolean keyWordEnd) {
            this.isKeyWordEnd = keyWordEnd;
        }
    }

    //建立前缀树
    private TrieNode root = new TrieNode();

    @PostConstruct
    public  void init(){
        try (
                InputStream is = this.getClass().getClassLoader().getResourceAsStream("sensitive-words.txt");
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                ){
            String keyword;
            while((keyword = reader.readLine()) != null){
                this.addKeyword(keyword);
            }
        } catch (Exception e) {
            logger.error("打开敏感文件失败" + e.getMessage());
            throw new RuntimeException(e);
        }
    }
    //将一个敏感词添加到前缀树
    private void addKeyword(String keyword){
        TrieNode tempNode = root;
        for(int i = 0; i < keyword.length(); i++){
            char c = keyword.charAt(i);
            TrieNode subNode = tempNode.getSubNode(c);
            if(subNode == null){
                //初始化子节点
                subNode = new TrieNode();
                tempNode.addSubNode(c, subNode);
            }
            //指向子节点
            tempNode = subNode;
            //设置结束标识
            if(i == keyword.length()-1){
                tempNode.setKeyWordEnd(true);
            }
        }
    }
    //检索前缀树并模糊处理

    /**
     * 过滤敏感此
     * @param text 待过滤的文本
     * @return 过滤后的文本
     */
    public String filter(String text){
        if(StringUtils.isBlank(text)){
            return null;
        }
        //指针1 指向树
        TrieNode tempNode = root;
        //指针2 指向字符串
        int begin = 0;
        //指针3
        int position = 0;
        StringBuilder sb = new StringBuilder();
        while(position < text.length()){
            char c = text.charAt(position);
            //跳过符号
            if(isSymbol(c)){
                //若指针1 在根部,将此符号计入结果，让指针2向下走一步
                if(tempNode == root){
                    sb.append(c);
                    begin++;
                }
                //无论符号在开头还是在中间，指针3都向下走一步
                position++;
                continue;
            }
            //检查下级节点
            tempNode = tempNode.getSubNode(c);
            if(tempNode == null){
                //以begin开头的字符串不是敏感词
                sb.append(text.charAt(begin));
                //进入下一个位置
                begin++;
                position = begin;
                tempNode = root;
            }else if(tempNode.isKeyWordEnd()){
                sb.append(REPLACEMENT);
                position++;
                begin = position;
                tempNode = root;
            }else {
                //检查下一个字符
                position++;
            }
        }
        sb.append(text.substring(begin));
        return sb.toString();
    }

    //判断是否为符号
    private boolean isSymbol(char c){
        //0x9FFF - 0x2E80是东亚文字
        return !CharUtils.isAsciiAlphanumeric(c) && (c <0x2E80 || c > 0x9FFF);
    }

}
